package com.zsl.swing.redis.desktop.window.dialog;

import com.zsl.swing.redis.desktop.model.DbCountConfigEntity;
import com.zsl.swing.redis.desktop.type.BtnOptEnum;
import com.zsl.swing.redis.desktop.type.MainMenuEnum;
import com.zsl.swing.redis.desktop.utils.ConfigUtils;
import com.zsl.swing.redis.desktop.utils.DialogUtils;
import com.zsl.swing.redis.desktop.utils.LocationUtils;
import com.zsl.swing.redis.desktop.window.ZslRedisDesktopMainWindow;
import com.zsl.swing.redis.desktop.window.builder.ConfirmCancelBtnPanelBuilder;
import com.zsl.swing.redis.desktop.window.ext.JIntegerField;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;

public class DbCountConfigDialog extends JDialog implements ActionListener {

    private int width = 600;

    private int height = 200;

    private JIntegerField dbCountField = new JIntegerField(40);

    private DbCountConfigDialog(){
        super(ZslRedisDesktopMainWindow.getMainWindow());
        this.setTitle(MainMenuEnum.DB_COUNT_SET.getText());
        this.setSize(width,height);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        this.initPanel();
        LocationUtils.locateCenter(this, width, height);

        this.setVisible(true);
    }

    private void initPanel() {
        this.dbCountField.setInteger(ZslRedisDesktopMainWindow.getDbCountConfig().getDbCount());

        Box verticalBox = Box.createVerticalBox();
        verticalBox.add(new JLabel(MainMenuEnum.DB_COUNT_SET.getText()));
        verticalBox.add(this.dbCountField);
        verticalBox.add(ConfirmCancelBtnPanelBuilder.getInstance(this));

        JPanel panel = new JPanel();
        panel.add(verticalBox);
        this.setContentPane(panel);
    }

    public static void showDialog(){
        new DbCountConfigDialog();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if(BtnOptEnum.CANCEL.getText().equals(command)){
            this.dispose();
        }else
        if(BtnOptEnum.CONFIRM.getText().equals(command)){
            Integer dbCount = this.dbCountField.getInteger();
            if(Objects.isNull(dbCount) || dbCount < 1 || dbCount > 1000){
                DialogUtils.errorDialog(ZslRedisDesktopMainWindow.getMainWindow()," 数据库展示数量不能少于1个或者多于1000个！");
            }else{
                DbCountConfigEntity configEntity = new DbCountConfigEntity();
                configEntity.setDbCount(dbCount);

                boolean result = ConfigUtils.writeDbCountConfig(configEntity);
                if(result){
                    this.dispose();
                    DialogUtils.restartConfirmDialog(ZslRedisDesktopMainWindow.getMainWindow(),"设置数据库展示数量成功，重启后生效！");
                }else{
                    DialogUtils.errorDialog(ZslRedisDesktopMainWindow.getMainWindow(),"设置数据库展示数量失败！");
                }
            }
        }
    }
}
